package com.iepacj.mina;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.integration.jmx.IoSessionMBean;

import javax.management.*;
import java.lang.management.ManagementFactory;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by iEpac on 16/6/17.
 */
public class MainIOHandler extends IoHandlerAdapter {

    private static final ConcurrentHashMap<String, IoSession> sessions = new ConcurrentHashMap<>();


    @Override
    public void sessionClosed(IoSession session) throws Exception {
        System.out.println(" session  关闭  :: " + session);
    }

    @Override
    public void sessionOpened(IoSession session) throws Exception {
        System.out.println(" session 打开 :: " + session);
    }

    @Override
    public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
        System.out.println(" session 空闲  :: " + status.toString());

    }

    @Override
    public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
        super.exceptionCaught(session, cause);
        cause.printStackTrace();
    }

    @Override
    public void messageReceived(IoSession session, Object message) throws Exception {
        System.out.println("收到消息 :: " + message + " :: session :: " + session);

        JSONObject json = JSON.parseObject((String) message);

        Integer mt = json.getInteger("mt");

        switch (mt) {

            case 1 :
                requestConnection(session, json);
                break;

            case 2 :
                System.out.println("收到心跳 :: " + session + "  " + json.toJSONString());
                break;

            case 3 :
                sendMsg(json);
                break;
        }




    }


    private void requestConnection(IoSession session, JSONObject json) {

        String mid = json.getString("mid");

        System.out.println("建立长连接 :: id :: " + mid + " :: session :: " + session);

        IoSession oldSession = sessions.get(mid);

        if (oldSession != null) {
            return;
        }
        try {
            ObjectName acceptorName = new ObjectName("minaIoSession:type=sessionCache,name=" + mid);

            session.setAttribute("mid", mid);

            sessions.put(mid, session);
            MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
            IoSessionMBean ioSessionMBean = new IoSessionMBean(session);

            SessionMbean smbean = new SessionMbean();
            smbean.setSession(session);
            mbs.registerMBean(smbean, acceptorName);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void sendMsg(JSONObject json) {

        String rece = json.getString("rece");

        IoSession receSession = sessions.get(rece);

        if (receSession == null) {
            return;
        }

        System.out.println("给" + rece +  " 发送消息 :: " + json.toJSONString());

        receSession.write(json.toJSONString() + "\n");
    }


}

















